﻿using FE.Service.Contract;
using FE.Service.Repository.SqlSugar;
using FE.Shared;
using FE.Shared.Enum;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;

namespace fe.pdf.convert.jobs.webapp.Controllers
{
    public class DbSettingController : Controller
    {
        private readonly IAppService _appService;
        private readonly IMySqlDbContext _mySqlDb;
        private readonly ILogger<HomeController> _logger;

        public DbSettingController(ILogger<HomeController> logger
            , IAppService appService
            , IMySqlDbContext mySqlDb
            )
        {
            _appService = appService;
            _logger = logger;
            _mySqlDb = mySqlDb;
        }

        public IActionResult Index(HttpResult result)
        {
            if (result?.ResultCode > 0)
            {
                ViewBag.Msg = result.ErrorMsg;
                ViewBag.ResultCode = result.ResultCode;
            }

            var app = _appService.ReadAppSettings();

            if (app == null
                || app.ServerMySqlSettings == null
                || string.IsNullOrEmpty(app.ServerMySqlSettings.HostIp)
                || string.IsNullOrEmpty(app.ServerMySqlSettings.Username)
                || string.IsNullOrEmpty(app.ServerMySqlSettings.Password)
                || string.IsNullOrEmpty(app.ServerMySqlSettings.DatabaseName)
                || app.ServerMySqlSettings.Port <= 0)
            {
                return View();
            }

            return View(app.ServerMySqlSettings);
        }

        public IActionResult Update([Bind("HostIp,Port,DatabaseName,Username,Password")] MySqlSettings mySqlSettings)
        {
            var result = new HttpResult
            {
                ResultCode = 0
            };

            if (ModelState.IsValid)
            {
                //todo 这里可以校验,如果没有修改,则不需要保存文件
                _appService.SaveAppSettings(mySqlSettings);

                try
                {
                    var ok = _mySqlDb.TestConnection();
                    result.ResultCode = ok ? ResultCode.Success : ResultCode.Failed;
                }
                catch (Exception e)
                {
                    result.ResultCode = ResultCode.Failed;
                    result.ErrorMsg = e.Message;
                }
            }
            else
            {
                return View("Index", mySqlSettings);
            }

            return RedirectToAction(nameof(Index), "DbSetting", result);
        }
    }
}